package cn.aishua.network;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import cn.aishua.util.ImageLoader.CallBack;

public class DownloadPicTask
    extends AsyncTask<String, Void, Bitmap>
{

//    private ImageView imageView;

    //    private ImageCacheManager imageCacheManager;
    private CallBack callback;

    public DownloadPicTask(CallBack callback)
    {
//        this.imageView = imageView;
        this.callback = callback;

        //        imageCacheManager = ImageCacheManager.getImageCacheService( activity, ImageCacheManager.MODE_FIXED_MEMORY_USED,
        //            "memory" );
        //        imageCacheManager.setMax_Memory( 1024 * 1024 );
    }

    @Override
    protected Bitmap doInBackground( String... params )
    {
        //        try
        //        {
        ////            return imageCacheManager.downlaodImage( new URL( params[0] ) );
        //            URL url = new URL( params[0] );
        //            conn = (HttpURLConnection) url.openConnection();
        //            conn.setDoInput( true );
        //            conn.connect();
        //            InputStream inputStream = conn.getInputStream();
        //            bitmap = BitmapFactory.decodeStream( inputStream );
        //        }
        //        catch( MalformedURLException e )
        //        {
        //            Log.d( "Download picture", "MalformedURLException" );
        //        }
        //        return null;
        HttpURLConnection conn = null;
        Bitmap bitmap = null;
        Log.d( "DownloadPicAsyncTask", "url: " + params[0] );
        try
        {
            URL url = new URL( params[0] );
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput( true );
            conn.connect();
            InputStream inputStream = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream( inputStream );

        }
        catch( MalformedURLException e1 )
        {
            Log.e( "DownloadPicAsyncTask", e1.getMessage() );
        }
        catch( IOException e )
        {
            Log.e( "DownloadPicAsyncTask", e.getMessage() );
        }
        finally
        {
            conn.disconnect();
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute( Bitmap result )
    {
//        imageView.setImageBitmap( result );
        callback.onFinished( result );
    }

//    @Override
//    protected void onPreExecute()
//    {
//        imageView.setImageResource( R.drawable.member_pic );
//    }

}
